import { camelCase } from "lodash";
import { defineStore } from "pinia";
import { useLocalStorage } from "@vueuse/core";
// import { getUserInfo, userLogin } from '@/api/user.js'
import { dynamicRoutes } from "@/router/index.js";
import router from "../router";

export const useAuthStore = defineStore("auth", {
  state: () => {
    return {
      layoutRouteName: import.meta.env.VITE_LAYOUT_ROUTE_NAME,
      // 菜单树形结构
      treeMenus: [],
      // 当前用户的所有菜单
      menus: [],
      // 当前所有菜单，id为key,value为menu
      menusObj: {},
      // 登录状态 success, failed
      loginStatus: false,
      // 路由白名单，可以直接跳转
      whiteList: ["/register"],
      // 当前登录的token ，持久化到本地储存
      token: "",
      userInfo: {},
    };
  },
  actions: {
    getFirstRoute() {
      const arr = [...this.treeMenus];
      while (arr.length) {
        const menu = arr.shift();
        if (!menu) return;
        if (menu.type === "menu") return menu;
        if (menu.children?.length) {
          arr.unshift(...menu.children);
        }
      }
    },

    initMenu() {
      console.log(this.menus, "this.menus");

      const handleTree = (data, pid) => {
        function tree(id) {
          let arr = [];
          data
            .filter((item) => {
              return item.meta.parentId === id;
            })
            .forEach((item) => {
              arr.push({
                ...item,
                children: tree(item.meta.id),
              });
            });
          return arr;
        }
        return tree(pid);
      };

      // // 转为树形结构
      this.treeMenus = handleTree(this.menus, null);
      this.treeMenus.forEach((item) => {
        router.addRoute("layout", item);
      });
    },

    //改造后端传递过来的路由参数
    changeRoutesInfo(routes) {
      const viewsComponent = import.meta.glob("@/views/**/*.vue");
      return routes.map((i) => {
        // 路由路径
        const path = i.path;

        // 路由全路径
        const fullPath =
          "/" +
          this.getMenuLevelArr(routes, i.id)
            .map((i) => i.path)
            .join("/");
        // const fullPath = `/${path}`
        i.fullPath = fullPath;
        // if (i.type === 'menu' && ['route', 'iframe'].includes(i.handleType)) {
        // 路由名称
        const name = i.name;
        // 组件name
        const componentName = camelCase(fullPath);
        let dynamicRoute = {};
        if (i.type === "menu") {
          dynamicRoute = {
            name,
            path,
            fullPath,
            component: viewsComponent[i.component],
            meta: {
              title: i.title,
              cache: i.cache,
              component: i.component,
              icon: i.icon,
              activeIcon: i.activeIcon,
              componentName,
              id: i.id,
              parentId: i.parentId,
              type: i.type,
              activeMenu:
                i.parentId === 0 || i.parentId === null
                  ? fullPath
                  : routes.find((item) => item.id === i.parentId).fullPath,
              hidden: i.hidden,
            },
          };
        } else {
          dynamicRoute = {
            name,
            path,
            fullPath,
            meta: {
              title: i.title,
              cache: i.cache,
              component: i.component,
              icon: i.icon,
              activeIcon: i.activeIcon,
              componentName,
              type: i.type,
              id: i.id,
              activeMenu: fullPath,
              parentId: i.parentId,
              hidden: i.hidden,
            },
          };
        }
        return dynamicRoute;
      });
    },
    getMenuLevelArr(routes, id) {
      const arr = [];

      let menusObj = {};
      routes.forEach((i) => {
        i.children = [];
        menusObj[i.id] = i;
      });

      let currentMenu = menusObj[id];
      while (currentMenu) {
        arr.unshift(currentMenu);
        currentMenu = menusObj[currentMenu.parentId];
      }
      return arr;
    },
    async beforeEach(to) {
      // 白名单直接跳转
      // if (this.whiteList.includes(to.fullPath)) {
      //   return
      // }
      // let path
      // if (this.token && !this.loginStatus) {
      //   // 初始化登录逻辑
      //   this.loginStatus = 'success' // 登录成功

      //   this.menus = this.changeRoutesInfo(dynamicRoutes)
      //   this.initMenu()
      //   return to.fullPath
      // }

      // 如果是登录失败的，直接跳转到登录页
      // if (this.loginStatus !== 'success') {
      //   path = '/login'
      // } else {
      //   // 如果是登录成功的，并且路由是根路径或者登录页的，跳转到菜单第一个路由
      //   if (['/', '/login'].includes(to.fullPath)) {
      //     path = this.getFirstRoute()?.fullPath
      //     console.log(path, 'pathpathpath')
      //   } else {
      //     return path
      //   }
      // }

      let path;
      if (!this.loginStatus) {
        // 初始化登录逻辑
        this.loginStatus = "success"; // 登录成功

        this.menus = this.changeRoutesInfo(dynamicRoutes);
        this.initMenu();
        return to.fullPath;
      }

      // 重定向路由和原跳转路由路径相同，则无需处理
      if (to.fullPath !== path) {
        return path;
      }
    },
    setToken(val) {
      this.token = val;
    },

    async setLoginUserInfo(loginUserInfo) {
      this.loginStatus = "success"; // 登录成功
      this.setToken(loginUserInfo.access_token);
      // await getUserInfo().then(async (res) => {
      //   this.userInfo = res.data
      //   this.menus = this.changeRoutesInfo(loginUserInfo.menus)

      //   this.initMenu()
      // })
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: sessionStorage,
        paths: ["userInfo", "token"],
      },
    ],
  },
});
